<template>
  <div
    v-loading="isLoading"
    class="panel-property"
  >
    <div class="content">
      <PanelLabelOverflowTooltip
        ref="panelLabelOverflowTooltip"
        :component-style="form.componentStyle"
      />
      <el-form
        ref="form"
        v-panel-label-overflow-tooltip="getPanelLabelOverflowTooltip()"
        class="prop-form"
        label-position="right"
        :model="form"
        :rules="rules"
        label-width="30%"
      >
        <OptionCollapse>
          <el-collapse-item
            :title="$demoi18n('panel.label.titleStyle')"
            name="cssStyle.title"
          >
            <BaseOption
              :form="form"
              option="title"
            />
            <BaseOption
              :form="form"
              option="cssStyle.title"
              :df-css-style-attrs="dfCssStyleAttrs.title"
            />
          </el-collapse-item>
        </OptionCollapse>
        <BaseOption
          :form="form"
          option="xAxisName"
        />
        <BaseOption
          :form="form"
          option="tooltipHasLabel"
          :widget-instance-id="widgetInstanceId"
          :config="config"
          type="echart"
        />
        <BaseOption
          :form="form"
          option="barShow"
        />
        <BaseOption
          :form="form"
          option="barNum"
        />
        <BaseOption
          :form="form"
          option="chartPadding"
        />
        <BaseOption
          :form="form"
          option="yAxisNameLeft"
        />
        <BaseOption
          :form="form"
          option="padding.left"
        />
        <BaseOption
          :form="form"
          option="padding.bottom"
        />
        <BaseOption
          :form="form"
          option="padding.right"
        />
        <BaseOption
          :form="form"
          option="xLabelRotate"
        />
        <BaseOption
          :form="form"
          option="componentStyle"
          @change="componentStyleChanged"
        />

        <div class="config-table mapping-table">
          <el-button
            plain
            class="btn-sure"
            type="primary"
            size="default"
            icon="Plus"
            :disabled="form.data.length > 7"
            @click.stop="addYAxis()"
          >
            {{ $demoi18n('word.LongitudinalAxis') }}
          </el-button>
          <el-table
            class="config-panel-table"
            :data="form.data"
            :row-style="{ height: '25px' }"
            :header-row-style="{ height: '25px' }"
            :header-cell-style="{ lineHeight: '15px' }"
          >
            <el-table-column
              prop="yAxisId"
              :label="$demoi18n('word.LongitudinalAxis')"
              width="45"
            ></el-table-column>
            <el-table-column
              prop="yAxisName"
              :label="$demoi18n('label.axisName')"
              min-width="50"
            >
              <template #default="scope">
                <VsFormItem
                  :prop="`data[${scope.$index}].yAxisName`"
                  :rules="
                    generateRules({
                      required: false,
                      label: $demoi18n('label.axisName'),
                    })
                  "
                >
                  <el-input
                    v-model="scope.row.yAxisName"
                    size="default"
                  ></el-input>
                </VsFormItem>
              </template>
            </el-table-column>
            <el-table-column
              prop="chartType"
              :label="$demoi18n('panel.commonX.chartType')"
              min-width="58"
            >
              <template #default="scope">
                <VsFormItem
                  :prop="`data[${scope.$index}].chartType`"
                  :rules="
                    generateRules({
                      required: false,
                      label: $demoi18n('panel.commonX.chartType'),
                    })
                  "
                >
                  <el-select
                    v-model="scope.row.chartType"
                    class="chartType-select"
                    :class="'panel-data-select-' + xvueTheme"
                    :popper-class="'select-poper-' + xvueTheme"
                    placeholder
                    size="default"
                    @focus="setMaxWidth"
                    @visible-change="setTagTitle($event)"
                    @change="optionChange(scope.row)"
                  >
                    <el-option
                      v-for="item in chartTypeOption"
                      :key="item.id"
                      class="panel-data-select-option"
                      :label="item.label"
                      :value="item.value"
                      :style="selectStyle"
                    ></el-option>
                  </el-select>
                  <el-button
                    class="chartType-setting"
                    icon="Setting"
                    :link="true"
                    type="primary"
                    @click.stop="setRow(scope)"
                  ></el-button>
                </VsFormItem>
              </template>
            </el-table-column>

            <el-table-column
              :label="$demoi18n('word.operation')"
              width="40"
            >
              <template #default="scope">
                <el-button
                  icon="Delete"
                  :link="true"
                  type="primary"
                  :disabled="form.data.length === 1"
                  @click.stop="deleteRow(scope)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <ChartOptionSetting
        ref="myChartOptionSetting"
        :component-style="form.componentStyle"
        @save="saveTheChartOption"
      />
    </div>
    <PanelPropertyBottom :config="config" :widgetInstanceId="widgetInstanceId" :form="form" />
  </div>
</template>
<script>
import OptionCollapse from '@/components/common/base-option/option-collapse/option-collapse.vue';
import PanelLabelOverflowTooltip from '@/components/common/overflow-tooltip/overflow-tooltip.vue';
import panelPropertyBase from '@/mixin/panel-property-base.js';
import { colorRGB2Hex, objHas } from '@/utils/util';
import BaseOption from '../../common/base-option/base-option.vue';
import ChartOptionSetting from './chartOptionSetting';
import colorGroup from './colorGroup.js';
import defaultOption from './defaultOption';
import EventBus from '@/event-bus/EventBus.js';

export default {
  name: 'PanelProperty',
  components: {
    BaseOption,
    ChartOptionSetting,
    OptionCollapse,
    PanelLabelOverflowTooltip,
  },
  mixins: [panelPropertyBase],
  props: ['config', 'widgetInstanceId', 'widget'],
  emits: ['updatePanelPropertyFormData'],
  data() {
    return {
      xvueTheme: window._adoPremise.uc.theme,

      activeColorRadio: '#2D8CF0', // 单选框选中时的颜色
      isLoading: false,
      chartTypeOption: [
        {
          label: this.$demoi18n('word.echart.bar'),
          value: 'uniaxial-bar',
        },
        {
          label: this.$demoi18n('word.echart.line'),
          value: 'uniaxial-line',
        },
        {
          label: this.$demoi18n('word.echart.scatter'),
          value: 'scatter',
        },
      ],
      selectedChartOption: null,
      form: {},
      selectStyle: {
        maxWidth: '',
      },
      dfCssStyleAttrs: {},
    };
  },
  computed: {},
  watch: {
    'form.componentStyle'() {
      if (this.form.cssStyle.title.color === '#3c3c3c' || this.form.cssStyle.title.color === '#00f7ff') {
        this.form.cssStyle.title.color = this.form.componentStyle === 'dark' ? '#00f7ff' : '#3c3c3c';
      }
    },
  },
  created() {
    if (this.config) {
      this.form = JSON.parse(JSON.stringify(this.config.config.property));
      const initPadding = {
        left: 50,
        bottom: 40,
        right: 0,
      };
      this.form.padding = this.form.padding || initPadding;
    }
    this.dfCssStyleAttrs = this.initDfCssStyleAttrs();
  },
  mounted() {
    // 添加参考线兼容
    this.initOption();
  },
  methods: {
    getPanelLabelOverflowTooltip() {
      return {
        parentComp: this,
      };
    },
    initOption() {
      if (this.form.data.length <= 0) {
        return;
      }
      this.form.data.forEach(item => {
        if (
          (item.chartType === 'uniaxial-bar' || item.chartType === 'uniaxial-line') &&
          !objHas(item.option, 'isMarklineShow')
        ) {
          item.option = {
            ...item.option,
            isMarklineShow: true,
            hasMarkLine: false,
            markLine: [
              {
                value: '',
                color: item.chartType === 'uniaxial-bar' ? '#FF0000' : '#00ACFF',
              },
            ],
          };
        }

        // 将rgb颜色转为hex
        if (item.option.hasMarkLine !== null) {
          this.colorCompatible(item.option.markLine);
        }
      });
    },
    colorCompatible(markLine) {
      markLine.forEach(item => {
        item.color = colorRGB2Hex(item.color);
      });
    },

    // 设置下拉option的title属性
    setTagTitle($event) {
      if (!$event) {
        return;
      }
      const dropdownList = document.querySelectorAll('.el-select-dropdown');
      dropdownList.forEach(item => {
        const options = item.querySelectorAll('.el-select-dropdown__item');
        options.forEach(element => {
          element.setAttribute('title', element.innerText);
        });
      });
    },

    // 设置 下拉option 的最大宽度
    setMaxWidth(val) {
      // this.selectStyle.maxWidth = `${val.srcElement.clientWidth}px`;
    },

    /*
     * 增加一行数据
     * 数据页签数据响应变化
     */
    addYAxis() {
      const { length } = this.form.data;
      this.form.data.push({
        id: `id_${new Date().getTime()}`,
        yAxisId: `y${length + 1}`,
        yAxisName: '',
        chartType: 'uniaxial-bar',
        option: this.getDefaultOptionByType('uniaxial-bar'),
      });
      EventBus.$emit('updatePanelPropertyFormData', this.form.data);
    },

    // 获取图表默认配置
    getDefaultOptionByType(type) {
      return defaultOption[type];
    },
    setRow(scope) {
      this.$refs.myChartOptionSetting.openDialog(scope);
    },
    deleteRow(scope) {
      // 删除后重新给yAxisId命名
      this.form.data.splice(scope.$index, 1);
      this.form.data.forEach((item, index) => {
        item.yAxisId = `y${index + 1}`;
      });
      EventBus.$emit('updatePanelPropertyFormData', this.form.data);
    },

    // 组件风格切换，重置表单颜色配置
    componentStyleChanged(val) {
      this.form.data.forEach(item => {
        const keys = Object.keys(colorGroup[val][item.chartType]);
        item.option.componentStyle = val;
        item.option.color = keys[0];
        const splitLineColor = val === 'light' ? '#E9E9E9' : '#193144';
        try {
          item.option.echart.xAxis.splitLine.lineStyle.color = splitLineColor;
        } catch (e) {}
        try {
          item.option.echart.yAxis.splitLine.lineStyle.color = splitLineColor;
        } catch (e) {}
      });
      this.initTitleColor();
    },
    optionChange(row) {
      row.option = this.getDefaultOptionByType(row.chartType);
      EventBus.$emit('updatePanelPropertyFormData', this.form.data);
    },
    saveTheChartOption(scope) {
      this.form.data.splice(scope.$index, 1, scope.row);
    },
  },
};
</script>

<style lang="less" scoped>
@import '../../common/less/panel-property.less';
</style>
<style lang="less" scoped>
.panel-property {
  .content {
    .prop-form {
      padding: 0 10px;

      .slider-number-left {
        vertical-align: text-bottom;
        padding-right: 20px;
      }
      .slider-number-right {
        vertical-align: text-bottom;
        padding-left: 20px;
      }

      :deep(.el-slider) {
        display: inline-block;
        width: 120px;
      }

      :deep(.el-form-item) {
        margin-bottom: 0;
      }
      .input-number {
        width: 80px;
        :deep(.el-input-number__decrease) {
          width: 19px;
          background-color: #fff;
        }
        :deep(.el-input-number__increase) {
          width: 19px;
          background-color: #fff;
        }
        :deep(.el-input__inner) {
          padding-left: 19px;
          padding-right: 19px;
        }
      }
      .input-number-left {
        margin-right: 25px;
      }

      .config-table {
        :deep(.el-table) {
          .cell {
            padding: 0 3px !important;
            .el-input__inner {
              padding: 0 5px !important;
            }
          }
          td,
          th {
            padding: 5px 0 !important;
          }
          .el-table__row > td {
            border: none;
          }
          .chartType-select {
            width: calc(100% - 24px);
          }

          .chartType-setting {
            padding-left: 4px;
            padding-right: 4px;
          }
        }
      }

      .color-radio-group {
        background-color: #eeeeee;
        :deep(.el-radio-button__inner) {
          display: inline-block;
          padding: 2px 2px;
          border: 0;
          border-radius: 0;
          height: 24px;
          margin: 2px 2px;
          background: #eeeeee;
        }
        :deep(.is-active) {
          .el-radio-button__inner {
            background-color: #409eff;
          }
        }
      }
    }
  }
}
</style>
